
package com.xie.myRule;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.sun.org.apache.bcel.internal.generic.NEW;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

//自定义的随机方法

/**
 * 5次一轮询
 *
 */
public class MyRandomRule extends AbstractLoadBalancerRule {
    public static AtomicInteger total = new AtomicInteger(0);
    public static AtomicInteger index = new AtomicInteger(0);//当前获取的服务数

    public MyRandomRule() {
    }

    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();

                //===========================自定义算法
                int a = total.get();
                int b = index.get();
                if(a<5){
                    server = upList.get(b);
                    total.incrementAndGet();
                    System.out.println("total:"+total.get());
                }else {
                    total = new AtomicInteger(0);
                    index.incrementAndGet();
                    if(b<=upList.size()){
                        server = upList.get(index.get());
                    }else{
                        index = new AtomicInteger(0);
                        server = upList.get(0);
                    }
                }



                //===========================


                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
